package com.revenant.driver.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.revenant.driver.R;
import com.revenant.driver.adapter.Driver.CarManageAdapter;
import com.revenant.driver.base.BaseActivity;
import com.revenant.driver.bean.BaseBean.MessageEvent;
import com.revenant.driver.bean.Driver.CarManageListBean;
import com.revenant.driver.bean.Driver.SearchEmptyBean;
import com.revenant.driver.utils.GsonUtil;
import com.revenant.driver.utils.SPUtils;
import com.revenant.driver.utils.Utils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;


import static com.revenant.driver.bean.BaseBean.MyEventCode.RenZhengCode;
import static com.revenant.driver.bean.BaseBean.MyEventCode.RenZhengCode32;
import static com.revenant.driver.utils.Constants.Driver_Car_VelManage_New;
import static com.revenant.driver.utils.Constants.Driver_Car_VelManage_delete_New;
import static com.revenant.driver.utils.Constants.alerttexta;
import static com.revenant.driver.utils.Constants.alerttextb;
import static com.revenant.driver.utils.Constants.alerttextc;
import static com.revenant.driver.utils.Constants.popMessage;

public class DriverVehicleManageActivity extends BaseActivity {
    @BindView(R.id.add_empety_car)
    TextView addEmpetyCar;
    @BindView(R.id.jiehuocheliangrecy)
    RecyclerView jiehuocheliangrecy;
    @BindView(R.id.jiehuocheliangsmart)
    SmartRefreshLayout jiehuocheliangsmart;
    private CarManageAdapter mItemAdapter;
    private Context context;

    private int pagernum = 1;

    private static final int MIN_CLICK_DELAY_TIME = 1000;
    private static long lastClickTime;
    private int buquanguachetype = -1;


    @Override
    public int getContentViewResId() {
        return R.layout.activity_driver_vehiclemanage;
    }

    @Override
    public void initView() {
        setcenterTitle("车辆管理");
        context = this;
        mItemAdapter = new CarManageAdapter();
        jiehuocheliangrecy.setLayoutManager(new LinearLayoutManager(context));
        jiehuocheliangrecy.setAdapter(mItemAdapter);
        jiehuocheliangsmart.autoRefresh();

//        selectPopMessage(context);

        Bundle bundle = getIntent().getExtras();
        if (bundle!=null){
            if (bundle.containsKey("buquanguachetype")){
                buquanguachetype = bundle.getInt("buquanguachetype", -1);
                if (buquanguachetype == 0) {
                    selectPopMessage(context);
                }
            }
        }

    }

    @Override
    public void leftbarclick() {
        super.leftbarclick();
        finish();
    }

    @Override
    public void initData() {

        jiehuocheliangsmart.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pagernum++;
                initDataRecyclerview();
                jiehuocheliangsmart.finishLoadMore(true);//加载完成
            }
        });
        //刷新
        jiehuocheliangsmart.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pagernum = 1;
                mItemAdapter.setNewData(null);
                initDataRecyclerview();
                jiehuocheliangsmart.finishRefresh(true);//刷新完成
            }
        });


        mItemAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.delete) {


                    new SweetAlertDialog(context, SweetAlertDialog.NORMAL_TYPE)
                            .setTitleText("确定删除吗")
                            .setCancelText("取消")
                            .setConfirmText("确定")
                            .showCancelButton(true)
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    if (Utils.isFastClick()) {

                                        showDig();
                                        getGoodsDetail(String.valueOf(mItemAdapter.getData().get(position).getId()), SPUtils.getAccounId(context), position, sweetAlertDialog);

                                    }

                                }
                            })
                            .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sDialog) {
                                    sDialog.dismissWithAnimation();
                                }
                            })
                            .show();

                }

            }
        });

        mItemAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (Utils.isFastClick()) {
                    switch (mItemAdapter.getData().get(position).isStatus()) {
                        case 0:
                            selectPopMessage(context);
                            break;
                        case 1:
                            selectPopMessage(context, popMessage.get(1), position);
                            break;
                        case 2:
                            editcheliang(position);
                            break;
                    }
                }


            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.add_empety_car)
    public void onViewClicked() {
//        Bundle bundle = new Bundle();
//        bundle.putString("cartypeid", "-1");
//        startActivity(DriverIAddVetticalActivity.class, bundle);
        startActivity(AddNewVertivalActivity.class);
    }

    private void getGoodsDetail(String id, int accountId, int pos, SweetAlertDialog sweetAlertDialog) {
        OkGo.<String>post(Driver_Car_VelManage_delete_New)

                .params("id", id)
                .params("accountId", accountId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dismissDig();
                        SearchEmptyBean g = GsonUtil.parseJsonWithGson(response.body(), SearchEmptyBean.class);
                        if (g.getCode().equals("0")) {
                            sweetAlertDialog.dismissWithAnimation();
                            showToast(g.getMsg());
                            mItemAdapter.remove(pos);
                        } else {
                            showToast(g.getMsg());
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDig();
                    }
                });
    }

    private void initDataRecyclerview() {

        OkGo.<String>get(Driver_Car_VelManage_New)

                .params("accountId", SPUtils.getAccounId(context))
//                .params("accountId", "82")
                .params("pageNum", pagernum)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        CarManageListBean shipperPublishedBean = GsonUtil.parseJsonWithGson(response.body(), CarManageListBean.class);
                        if (shipperPublishedBean.getCode().equals("0")) {
                            int pageNum = shipperPublishedBean.getData().getPageNum();
                            int pages = shipperPublishedBean.getData().getPages();
                            if (pageNum == 1) {
                                mItemAdapter.setNewData(shipperPublishedBean.getData().getResult());
                            } else if (pageNum <= pages) {
                                mItemAdapter.addData(shipperPublishedBean.getData().getResult());
                            } else {
                                mItemAdapter.loadMoreEnd();
                            }

                        } else {
                            mItemAdapter.loadMoreFail();
                            showToast(shipperPublishedBean.getMsg());
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        jiehuocheliangsmart.autoRefresh();
    }


    private void selectPopMessage(Context context, String message, int position) {
        AlertDialog alertDialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View view = getLayoutInflater().inflate(R.layout.popselectmessage, null);
        TextView text = view.findViewById(R.id.popselectmessage);
        text.setText(message);

        TextView cancel = view.findViewById(R.id.cancel);
        TextView ok = view.findViewById(R.id.confirm);

        builder.setView(view);

        alertDialog = builder.show();

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();

            }
        });

        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                editcheliang(position);
            }
        });
    }


    private void selectPopMessage(Context context) {
        AlertDialog alertDialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View view = getLayoutInflater().inflate(R.layout.popbuquanguachemessage, null);
        TextView texta = view.findViewById(R.id.popselectmessagea);
        texta.setText(alerttexta);
        TextView textb = view.findViewById(R.id.popselectmessageb);
        textb.setText(alerttextb);
        TextView textc = view.findViewById(R.id.popselectmessagec);
        textc.setText(alerttextc);

        textb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.callPhone(DriverVehicleManageActivity.this, textb.getText().toString());
            }
        });

        TextView ok = view.findViewById(R.id.confirm);

        builder.setView(view);

        alertDialog = builder.show();

        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
    }


    private void editcheliang(int position) {
        if (mItemAdapter.getData().get(position).isStatus() == 2 || mItemAdapter.getData().get(position).isStatus() == 1) {
            finish();
            Bundle bundle = new Bundle();
            bundle.putString("cartypeid", mItemAdapter.getData().get(position).getId());
            startActivity(CarManageEditActivity.class, bundle);
        }
    }


    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }


    @Override
    protected void receiveStickyEvent(MessageEvent event) {
        super.receiveStickyEvent(event);
        switch (event.getCode()) {
            case RenZhengCode32:
//                getpseronal();
                jiehuocheliangsmart.autoRefresh();
                break;
        }
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }
}
